import { RootState } from '@/types/store'
import { Input, NavBar, TextArea } from 'antd-mobile'
import { InputRef } from 'antd-mobile/es/components/input'
import { TextAreaRef } from 'antd-mobile/es/components/text-area'
import { useEffect, useRef, useState } from 'react'
import { useSelector } from 'react-redux'

import styles from './index.module.scss'
type props = {
  hideInput: () => void
  type: '' | 'name' | 'intro'
  onUpdata: (key: string, value: string) => void
}
const EditInput = ({ hideInput, type, onUpdata }: props) => {
  const name = type === 'name' ? '昵称' : '简介'
  const { profile } = useSelector((state: RootState) => state.Profile)
  const [value, setValue] = useState(
    type === 'name' ? profile.name : profile.intro
  )
  const inputRef = useRef<InputRef>(null)
  const textRef = useRef<TextAreaRef>(null)
  useEffect(() => {
    if (type === 'name') {
      inputRef.current?.focus()
    } else {
      textRef.current?.focus()
      document.querySelector('textarea')?.setSelectionRange(-1, -1)
    }
  }, [type])
  return (
    <div className={styles.root}>
      <NavBar
        className="navbar"
        right={
          <span className="commit-btn" onClick={() => onUpdata(type, value)}>
            提交
          </span>
        }
        onBack={hideInput}
      >
        编辑{name}
      </NavBar>

      <div className="edit-input-content">
        <h3>{name}</h3>

        <div className="input-wrap">
          {type === 'name' ? (
            <Input
              placeholder="请输入"
              value={value}
              onChange={(e) => setValue(e)}
              ref={inputRef}
            />
          ) : (
            <TextArea
              className="textarea"
              placeholder="请输入简介"
              showCount
              maxLength={99}
              value={value}
              onChange={(e) => setValue(e)}
              ref={textRef}
            />
          )}
        </div>
      </div>
    </div>
  )
}

export default EditInput
